import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNodesData, useReactFlow } from '@xyflow/react';
import './style.less'
import { Dropdown, Input, Modal } from 'antd';
import { CopyOutlined, DeleteOutlined, DisconnectOutlined, EditOutlined, SnippetsOutlined, ZoomInOutlined } from '@ant-design/icons';
import useContextMenuStore from '@/store/ContextMenu';
import * as  _ from 'lodash-es'
import { randomUUID } from '@/utils/dataflow';
import useDesignerStore from '@/store/Designer';

function ContextMenu() {
    const { setNodes, setEdges, setCenter, updateNodeData, getNode } = useReactFlow();
    const { visible, top, left, closeContext, target } = useContextMenuStore()
    const nodeNameRef = useRef(null)
    const currentNode = useNodesData(target?.id)
    const [key, setKey] = useState(randomUUID())
    const { drawerHeight } = useDesignerStore()

    useEffect(() => {
        setKey(randomUUID())
    }, [top, left, target])


    const onDeleteNode = useCallback(() => {
        setNodes((nodes) => nodes.filter((node) => node.id !== currentNode?.id));
        setEdges((edges) => edges.filter((edge) => edge.source !== currentNode?.id && edge.target !== currentNode?.id));
    }, [setNodes, setEdges, currentNode]);

    const onRenameNode = () => {
        const RenameContent = () => {
            return <Input ref={nodeNameRef} defaultValue={currentNode?.data?.label} autoFocus maxLength={10}/>
        }
        Modal.confirm({
            title: '重命名节点',
            content: <RenameContent />,
            onOk: () => {
                nodeNameRef.current?.input?.value && 
                updateNodeData(target?.id, { label: nodeNameRef.current?.input?.value })
            },
            okText: '确定',
            cancelText: '取消',
        })

    }


    const onCopyNode = useCallback(() => {
        if (!currentNode) return
        // setNodes((nodes) => ([...nodes, { ...currentNode, id: uuid(), }])
    }, [setNodes, setEdges, currentNode]);


    const onPasteNode = useCallback((e) => {
        const copy = _.pick(currentNode, ['id', 'type', 'measured', 'position', 'data'])
        copy.id = randomUUID()
        const labelSplits = currentNode?.data?.label?.split('_')
        const oldIdx = Number(labelSplits?.[1] ?? 0)
        const num = Number.isNaN(oldIdx) ? 1 : oldIdx + 1
        copy.data = {
            ...copy.data,
            label: labelSplits?.[0] + '_' + num
        }
        copy.position = {
            x: copy.position.x + (copy.measured.width || 50),
            y: copy.position.y + (copy.measured.height || 50)
        }
        setNodes((nodes) => ([...nodes, copy]))
    }, [setNodes, setEdges, currentNode]);

    const onFocusNode = () => {
        const pos = getNode(currentNode?.id)?.position;
        if (pos) {
          const offsetY = drawerHeight / 2;
          setCenter(pos.x, pos.y + offsetY, { duration: 500, zoom: 1 });
        }
    }

    // 监听全局点击事件
    // useEffect(() => {
    //     const handleClickOutside = (event) => {
    //         event.preventDefault()
    //         const paths = event.composedPath()
    //         for (const path of paths) {
    //             if (path.classList?.contains('react-flow__pane')) { //画布
    //                 console.debug('画布')
    //                 return
    //             } else if (path.classList?.contains('react-flow__node')) { //节点
    //                 console.debug('节点')
    //                 return
    //             } else if (path.classList?.contains('react-flow__edge-interaction')) { //边
    //                 console.debug('边')
    //                 return
    //             }
    //         }
    //         closeContext()
    //     };
    //     document.addEventListener("contextmenu", handleClickOutside);
    //     document.addEventListener("click", closeContext);
    //     return () => {
    //         document.removeEventListener("click", closeContext);
    //         document.removeEventListener("contextmenu", handleClickOutside);
    //     };
    // }, []);

    const items = useMemo(() => {
        const type = target?.type
        if (type === 'node') {
            return [
                {
                    label: '居中',
                    key: 'focusNode',
                    icon: <ZoomInOutlined />,
                    onClick: onFocusNode
                },
                {
                    label: '删除节点',
                    key: 'deleteNode',
                    icon: <DeleteOutlined />,
                    onClick: onDeleteNode
                },
                {
                    label: '重命名节点',
                    key: 'renameNode',
                    icon: <EditOutlined />,
                    onClick: onRenameNode
                },
                {
                    type: 'divider'
                },
                {
                    label: '复制',
                    key: 'copyNode',
                    icon: <CopyOutlined />,
                    onClick: onCopyNode
                },
                {
                    label: '粘贴',
                    key: 'pasteNode',
                    icon: <SnippetsOutlined />,
                    onClick: onPasteNode
                },
            ]
        }

        else if (type === 'edge') {
            return [
                {
                    label: '删除连线',
                    key: 'deleteNode',
                    icon: <DisconnectOutlined />
                },
            ]
        }
        return [
            {
                label: '复制',
                key: 'copy',
                icon: <CopyOutlined />
            },
            {
                label: '粘贴',
                key: 'pasteNode',
                icon: <SnippetsOutlined />
            },
        ]
    }, [target]);

    if (!visible) return null

    return (
        <Dropdown
            menu={{ items, onClick: closeContext }}
            overlayStyle={{ width: 150 }}
            key={key}
            open
        >
            <div
                style={{
                    position: "absolute",
                    top,
                    left,
                    zIndex: 100,
                }}
                className="context-menu"
            />
        </Dropdown>)

}

export default memo(ContextMenu)